package com.stutter.shared;

public class Stutter {
   	/**
	    * Check stutter.
	    * 
	    * Returns a string describe all repeated words in the input text.
	    * Reads the input text one line, then one word at a time.
	    * Looks for repeated words and adds to the return string.
	    * 
	    * @param input the input text
	    * 
	    * @return a string describe all repeated words
	    */
	public static String checkStutter(String input) {
		String lastWord = null;
		String result = new String();
		
		// Splits the input into lines and puts in an array of strings
		String[] lines = input.split("\n");
		
		for (int i = 0; i < lines.length; i++) {
			
			// do when this is not an empty line
			if (!lines[i].trim().isEmpty()) {
			
	   			// Splits the line into words all non alpha-numeric characters or white spaces and puts in an array of strings
	   			String[] words = lines[i].split ("(\\s|[^a-zA-Z0-9 ])+");
	
	   			// Compare with the last word on the previous line
	   			if (words [0].equalsIgnoreCase (lastWord))
	   				result += "Repeated word at line number " + (i+1) + ": " + words[0] + "<br>"; 
	
	   			// Stop before the end, nothing to compare the last word with
	   			for (int j = 0; j < (words.length-1); j++){
	   				// Check to see if the current and subsequent words are the same
	   				if (words [j].equalsIgnoreCase (words [j+1]))
	   	   				result += "Repeated word at line number " + (i+1) + ": " + words[j] + "<br>"; 
	            }
	
	   			
	   			// Save last word in the line
	   			lastWord = words [words.length-1];
			}
			
		}
			
		return result;
	}


}
